<template>
  <div class="project-implementation-stage app-container project-operate-container">
    <!-- 单个卡片容器 -->
    <div class="card-container">
      <!-- 顶部标签页 -->
      <el-tabs v-model="activeTab">
        <el-tab-pane label="项目实施" name="implementation">
          <!-- 项目编号和名称（不可折叠） -->
          <el-form :model="projectForm" label-width="120px" size="small">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="项目编号：">
                  <el-input
                    v-model="projectForm.projectNumber"
                    readonly
                    style="width: 454px"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目名称：">
                  <el-input
                    v-model="projectForm.projectName"
                    readonly
                    style="width: 454px"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <!-- 可折叠部分 -->
          <div class="project-info-collapse">
            <div
              :class="{ 'is-expanded': isExpanded }"
              class="collapse-content"
            >
              <el-form :model="projectForm" label-width="120px" size="small">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="计划时间：">
                      <el-input
                        v-model="projectForm.plannedStartTime"
                        readonly
                        style="width: 216px"
                      />
                      <span style="margin: 0px 5px">到</span>
                      <el-input
                        v-model="projectForm.plannedEndTime"
                        readonly
                        style="width: 216px"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="实际时间：">
                      <el-date-picker
                        v-model="projectForm.actualStartTime"
                        format="yyyy-MM-dd"
                        placeholder="开始日期"
                        style="width: 216px"
                        type="date"
                        value-format="yyyy-MM-dd"
                      >
                      </el-date-picker>
                      <span style="margin: 0px 5px">到</span>
                      <el-date-picker
                        v-model="projectForm.actualEndTime"
                        format="yyyy-MM-dd"
                        placeholder="结束日期"
                        style="width: 216px"
                        type="date"
                        value-format="yyyy-MM-dd"
                      >
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="产品名称：">
                      <el-input
                        v-model="projectForm.productName"
                        readonly
                        style="width: 454px"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <!-- 折叠箭头 -->
            <div class="collapse-header" @click="toggleCollapse">
              <i
                :class="['el-icon-arrow-right', { 'is-active': isExpanded }]"
              ></i>
            </div>
          </div>

          <!-- 分割线 -->
          <el-divider></el-divider>

          <!-- 实施阶段进度指示器 -->
          <div class="stage-progress">
            <div class="stage-title">实施阶段：</div>
            <div v-loading="stageLoading" class="stage-flow">
              <div
                v-for="(stage, index) in stages"
                :key="stage.processId"
                class="stage-node-wrapper"
              >
                <div
                  :class="{
                    'stage-node': true,
                    active: stage.status === 1, // 已完成（优先级最高）
                    current:
                      !stage.status &&
                      isStageInProgress(stage) &&
                      !isStageOverdue(stage), // 进行中且未过期
                    overdue: !stage.status && isStageOverdue(stage), // 未完成且已过期（包括未开始和进行中）
                    selected: selectedStage === index,
                  }"
                  class="stage-node"
                  @click="selectStage(index)"
                >
                  <el-tooltip :content="stage.processStageName" placement="top">
                    <div class="node-circle">
                      {{ stage.processStageName.substring(0, 4) }}
                    </div>
                  </el-tooltip>
                  <div class="stage-line"></div>
                </div>
                <div v-if="index < stages.length - 1" class="stage-arrow"></div>
              </div>
            </div>
          </div>

          <!-- 分割线 -->
          <el-divider></el-divider>

          <!-- 阶段时间信息 -->
          <div class="stage-time">
            <el-form
              ref="stageForm"
              :model="stageForm"
              :rules="rules"
              label-width="120px"
              size="small"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="阶段计划时间：">
                    <el-input
                      v-model="stageForm.plannedStartTime"
                      style="width: 216px"
                    />
                    <span style="margin: 0px 5px">到</span>
                    <el-input
                      v-model="stageForm.plannedEndTime"
                      style="width: 216px"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="阶段实际时间：" prop="actualTimeRange">
                    <el-date-picker
                      v-model="stageForm.actualStartTime"
                      format="yyyy-MM-dd"
                      placeholder="开始日期"
                      style="width: 216px"
                      type="date"
                      value-format="yyyy-MM-dd"
                    >
                    </el-date-picker>
                    <span style="margin: 0px 5px">到</span>
                    <el-date-picker
                      v-model="stageForm.actualEndTime"
                      format="yyyy-MM-dd"
                      placeholder="结束日期"
                      style="width: 216px"
                      type="date"
                      value-format="yyyy-MM-dd"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="阶段执行人：">
                    <el-input
                      v-model="executorPersonName"
                      style="width: 454px"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="阶段是否已完成：">
                    <el-select
                      v-model="stageForm.status"
                      placeholder="请选择阶段状态"
                      style="width: 454px"
                    >
                      <el-option :value="0" label="否" />
                      <el-option :value="1" label="是" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

          <!-- 阶段标签页 -->
          <el-tabs v-model="stageActiveTab" class="stage-tabs">
            <el-tab-pane label="阶段服务日志" name="serviceLog">
              <StageServiceLog
                :processId="
                  currentProcessData ? currentProcessData.processId : ''
                "
                :projectId="projectId"
              />
            </el-tab-pane>
            <el-tab-pane label="阶段施工费用" name="constructionCost">
              <div class="construction-cost">
                <!-- 顶部按钮组 -->
                <div class="operation-group">
                  <el-button
                    icon="el-icon-plus"
                    plain
                    size="mini"
                    type="primary"
                    @click="handleAddRow"
                    >新增
                  </el-button>
                  <el-button
                    icon="el-icon-download"
                    plain
                    size="mini"
                    type="warning"
                    @click="handleExport"
                    >导出
                  </el-button>
                  <el-button
                    icon="el-icon-download"
                    plain
                    size="mini"
                    type="warning"
                    @click="handleExportAll"
                    >全部导出
                  </el-button>
                </div>

                <!-- 费用列表 -->
                <el-table
                  :cell-style="{ padding: '0px' }"
                  :data="costList"
                  :row-style="{ height: '30px' }"
                  border
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                  @row-dblclick="handleRowDblClick"
                >
                  <el-table-column
                    align="center"
                    type="selection"
                    width="45"
                  ></el-table-column>
                  <el-table-column
                    align="center"
                    label="费用说明"
                    prop="costDescription"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-if="scope.row.isEdit"
                        v-model="scope.row.costDescription"
                        placeholder="请输入费用说明"
                        size="mini"
                      >
                      </el-input>
                      <span v-else>{{ scope.row.costDescription }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="费用类型"
                    prop="costType"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-if="scope.row.isEdit"
                        v-model="scope.row.costType"
                        placeholder="请输入费用类型"
                        size="mini"
                        width="100"
                      >
                      </el-input>
                      <span v-else>{{ scope.row.costType }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="金额"
                    prop="amount"
                    width="150"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-if="scope.row.isEdit"
                        v-model.number="scope.row.amount"
                        placeholder="请输入金额"
                        size="mini"
                      >
                      </el-input>
                      <span v-else>{{ scope.row.amount }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="产生时间"
                    prop="costTime"
                    width="150"
                  >
                    <template slot-scope="scope">
                      <el-date-picker
                        v-if="scope.row.isEdit"
                        v-model="scope.row.costTime"
                        placeholder="选择日期"
                        size="mini"
                        style="width: 100%"
                        type="date"
                        value-format="yyyy-MM-dd"
                      >
                      </el-date-picker>
                      <span v-else>{{ scope.row.costTime }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="操作" width="120">
                    <template slot-scope="scope">
                      <template v-if="scope.row.isEdit">
                        <el-button
                          size="small"
                          type="text"
                          @click="handleSaveRow(scope.row)"
                          >保存
                        </el-button>
                        <el-button
                          size="small"
                          type="text"
                          @click="handleCancelEdit(scope.$index)"
                          >取消
                        </el-button>
                      </template>
                      <template v-else>
                        <el-button
                          icon="el-icon-delete"
                          size="mini"
                          type="text"
                          title="删除"
                          @click="handleDeleteRow(scope.$index)"
                        ></el-button>
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
            <el-tab-pane label="阶段成果交付" name="delivery">
              <div class="delivery-content">
                <!-- 顶部按钮 -->
                <div class="operation-group">
                  <el-button
                    icon="el-icon-plus"
                    plain
                    size="mini"
                    type="primary"
                    @click="handleAddDelivery"
                    >新增
                  </el-button>
                </div>

                <!-- 成果交付列表 -->
                <el-table
                  :cell-style="{ padding: '0px' }"
                  :data="deliveryList"
                  :row-style="{ height: '30px' }"
                  border
                  style="width: 100%"
                  @row-dblclick="handleDeliveryRowDblClick"
                >
                  <el-table-column
                    align="center"
                    label="成果名称"
                    prop="deliverableName"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-if="scope.row.isEdit"
                        v-model="scope.row.deliverableName"
                        placeholder="请输入成果名称"
                        size="mini"
                      >
                      </el-input>
                      <span v-else>{{ scope.row.deliverableName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="成果是否必须"
                    prop="isRequired"
                    width="120"
                  >
                    <template slot-scope="scope">
                      <template v-if="scope.row.isEdit">
                        <el-select
                          v-model="scope.row.isRequired"
                          placeholder="请选择"
                          size="mini"
                        >
                          <el-option :value="1" label="是" />
                          <el-option :value="0" label="否" />
                        </el-select>
                      </template>
                      <template v-else>
                        <span>{{
                          scope.row.isRequired === 1 ? "是" : "否"
                        }}</span>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="交付时间"
                    prop="deliveryTime"
                    width="150"
                  >
                    <template slot-scope="scope">
                      <el-date-picker
                        v-if="scope.row.isEdit"
                        v-model="scope.row.deliveryTime"
                        placeholder="选择日期"
                        size="mini"
                        style="width: 100%"
                        type="date"
                        value-format="yyyy-MM-dd"
                      >
                      </el-date-picker>
                      <span v-else>{{
                        parseTime(scope.row.deliveryTime, "{y}-{m}-{d}")
                      }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="交付人"
                    prop="nickName"
                    width="140"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-if="scope.row.isEdit"
                        v-model="scope.row.nickName"
                        placeholder="请输入交付人"
                        size="mini"
                      >
                      </el-input>
                      <span v-else>{{ scope.row.nickName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="附件" width="100">
                    <template slot-scope="scope">
                      <!-- 编辑状态显示上传按钮 -->
                      <template v-if="scope.row.isEdit">
                        <el-button
                          size="mini"
                          type="primary"
                          @click="handleUploadClick(scope.row)"
                          >上传附件
                        </el-button>
                      </template>
                      <!-- 非编辑状态显示查看按钮 -->
                      <template v-else>
                        <el-button
                          plain
                          size="mini"
                          type="primary"
                          @click="queryUploadFile(scope.row.deliverableId)"
                          >查看
                        </el-button>
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="操作" width="120">
                    <template slot-scope="scope">
                      <template v-if="scope.row.isEdit">
                        <el-button
                          size="small"
                          type="text"
                          @click="handleSaveDelivery(scope.row)"
                          >保存
                        </el-button>
                        <el-button
                          size="small"
                          type="text"
                          @click="handleCancelDeliveryEdit(scope.$index)"
                          >取消
                        </el-button>
                      </template>
                      <template v-else>
                        <el-button
                          icon="el-icon-delete"
                          size="mini"
                          type="text"
                          @click="handleDeleteDelivery(scope.row)"
                          title="删除"
                        ></el-button>
                      </template>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
          </el-tabs>

          <!-- 底部按钮 -->
          <div class="bottom-buttons">
            <el-button type="primary" @click="submitForm">保 存</el-button>
            <el-button @click="cancel">关 闭</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="客户联系人" name="contacts">
          <el-row>
            <el-col :span="24">
              <el-table
                v-loading="loading"
                :cell-style="{ padding: '0px' }"
                :data="personList"
                :row-style="{ height: '30px' }"
                border
                height="450"
                highlight-current-row
              >
                <el-table-column
                  :index="indexMethod"
                  label="序号"
                  prop="index"
                  type="index"
                />
                <el-table-column
                  :show-overflow-tooltip="true"
                  align="center"
                  label="企业名称"
                  prop="enterpriseName"
                />
                <el-table-column
                  :show-overflow-tooltip="true"
                  align="center"
                  label="姓名"
                  prop="name"
                  width="100"
                />
                <el-table-column
                  :show-overflow-tooltip="true"
                  align="center"
                  label="性别"
                  prop="sex"
                  width="60"
                >
                  <template slot-scope="scope">
                    <dict-tag
                      :options="dict.type.sys_user_sex"
                      :value="scope.row.sex"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  :show-overflow-tooltip="true"
                  align="center"
                  label="职位"
                  prop="position"
                  width="120"
                />
                <el-table-column
                  :show-overflow-tooltip="true"
                  align="center"
                  label="联系方式"
                  prop="phone"
                  width="150"
                />
              </el-table>
              <pagination
                v-show="total > 0"
                :limit.sync="queryParams.pageSize"
                :page.sync="queryParams.pageNum"
                :total="total"
                @pagination="getList"
              />
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog
      :visible.sync="uploadDialogVisible"
      append-to-body
      title="上传附件"
      width="500px"
    >
      <el-form ref="uploadForm" :model="uploadForm" label-width="80px">
        <el-form-item label="附件">
          <file-view
            :key="refreshKey"
            :businessId="currentDeliveryId"
            :type="0"
            businessCode="stageDeliverable"
            @change="handleFileChange"
          ></file-view>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uploadDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUploadConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="viewDialogVisible" append-to-body width="700px">
      <el-table :data="fileList">
        <el-table-column align="center" label="文件名称" prop="fileName" />
        <el-table-column
          align="center"
          class-name="small-padding fixed-width"
          fixed="right"
          label="操作"
          width="120"
        >
          <template slot-scope="scope">
            <el-button
              icon="el-icon-view"
              size="mini"
              type="text"
              @click.stop="handleView(scope.row)"
            ></el-button>
            <el-button
              icon="el-icon-download"
              size="mini"
              type="text"
              @click="handleDownload(scope.row.url, scope.row.fileName)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img :src="dialogImageUrl" alt="" width="100%" />
    </el-dialog>
    <el-dialog :visible.sync="dialogVisiblePdf" append-to-body>
      <pdf
        v-for="item in pageTotal"
        :key="item"
        :page="item"
        :src="pdfUrl"
      ></pdf>
    </el-dialog>
  </div>
</template>

<script>
import FileView from "@/components/FileView/index";
import StageServiceLog from "./records.vue";
import {
  editProjectImplementation,
  getImplementation,
} from "@/api/project/implementation";
import { listPerson } from "@/api/enterprise/person";
import { getProjectPlanning } from "@/api/project/planning";
import { getUser } from "@/api/system/user";
import { deleteServiceLogByProjectId } from "@/api/project/log";
import {
  addBudget,
  delBudget,
  deleteProjectBudget,
  listBudget,
  updateBudget,
} from "@/api/project/cost";
import {
  addDeliverable,
  delDeliverable,
  listDeliverable,
  updateDeliverable,
} from "@/api/project/deliverable";
import { download } from "@/utils/request";
import { queryFile } from "@/api/system/file";
import pdf from "vue-pdf";

export default {
  name: "ProjectImplementationStage",
  dicts: ["sys_user_sex"],
  components: {
    StageServiceLog,
    FileView,
    pdf,
  },
  props: {
    implementationId: {
      type: String,
      default: "",
    },
    enterpriseId: {
      type: String,
      default: "",
    },
  },
  data() {
    const validateActualTime = (rule, value, callback) => {
      if (!this.stageForm.actualStartTime || !this.stageForm.actualEndTime) {
        callback(new Error("请选择完整的时间范围"));
      } else if (
        this.stageForm.actualEndTime < this.stageForm.actualStartTime
      ) {
        callback(new Error("结束日期不能早于开始日期"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      dialogVisiblePdf: false,
      dialogImageUrl: "",
      dialogImageUrlPdf: "",
      fileList: [],
      pageTotal: null,
      pdfUrl: "",
      uploadDialogVisible: false,
      viewDialogVisible: false,
      currentDeliveryId: "",
      uploadForm: {},
      refreshKey: 0,
      tempDeliveryList: [], // 临时存储编辑前的数据
      selectedCosts: [], // 新增：存储选中的费用记录
      stageFormsData: {},
      tempCostList: [], // 临时存储编辑前的数据
      executorPersonName: "",
      stageLoading: false,
      index: null,
      projectId: "",
      costList: [], // 费用列表
      deliveryList: [], // 成果交付列表
      activeTab: "implementation",
      stageActiveTab: "serviceLog",
      isExpanded: false,
      selectedStage: 0,
      // 总条数
      total: 0,
      loading: true,
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        enterpriseId: null,
        name: null,
        position: null,
        education: null,
        classificationId: null,
        enterpriseName: null,
      },
      queryDeliveryParams: {
        pageNum: 1,
        pageSize: 15,
        processId: null,
      },
      // 企业人员管理表格数据
      personList: [],
      currentProcessData: null,
      stages: [],
      projectForm: {
        projectId: "",
        projectNumber: "",
        projectName: "",
        plannedStartTime: "",
        plannedEndTime: "",
        actualStartTime: "",
        actualEndTime: "",
        productName: "",
      },
      stageForm: {
        processId: "",
        planningId: "",
        plannedStartTime: "",
        plannedEndTime: "",
        actualStartTime: "",
        actualEndTime: "",
        executorPerson: "",
        status: 0,
      },
      queryBudgetParams: {
        pageNum: 1,
        pageSize: 15,
        planningId: null,
        costDescription: null,
        costType: null,
        costTime: null,
        amount: null,
        processStage: null,
        useType: null,
      },
      rules: {
        actualTimeRange: [{ validator: validateActualTime, trigger: "blur" }],
      },
    };
  },
  async mounted() {
    await this.getProjectInfo();
    await this.updateStageStatus();
  },

  async updated() {
    await this.updateStageStatus();
  },
  created() {
    this.getProjectInfo();
    this.getList();
    this.getBudgetList();
    this.getDeliveryList();
  },
  methods: {
    getDeliveryList() {
      this.queryDeliveryParams = {
        ...this.queryDeliveryParams,
        processId:
          (this.currentProcessData && this.currentProcessData.processId) ||
          null,
      };
      listDeliverable(this.queryDeliveryParams).then(response => {
        this.deliveryList = response.rows || [];
      });
    },
    handleAddDelivery() {
      const newDelivery = {
        deliverableId: this.guid(),
        processId: this.currentProcessData.processId,
        deliverableName: "",
        deliveryTime: "",
        deliveryPerson: "",
        fileUrl: "",
        isEdit: true,
        isNew: true,
      };
      this.deliveryList.unshift(newDelivery);
    },

    handleDeliveryRowDblClick(row) {
      if (row.isEdit) return;
      this.tempDeliveryList[this.deliveryList.indexOf(row)] = { ...row };
      this.$set(row, "isEdit", true);
    },
    // 新增：处理选择变化
    handleSelectionChange(selection) {
      this.selectedCosts = selection;
    },

    async handleSaveDelivery(row) {
      // 验证必填字段
      if (!row.deliverableName || !row.deliverableName.trim()) {
        this.$message.warning("请填写成果名称");
        return;
      }
      if (!row.deliveryTime) {
        this.$message.warning("请选择交付时间");
        return;
      }

      try {
        const deliveryData = {
          deliverableId: row.deliverableId,
          processId: this.currentProcessData.processId,
          deliverableName: row.deliverableName,
          deliveryTime: row.deliveryTime,
          deliveryPerson: row.nickName,
          useType: 3,
        };

        let response;
        if (row.isNew) {
          response = await addDeliverable(deliveryData);
        } else {
          response = await updateDeliverable(deliveryData);
        }

        if (response.code === 200) {
          row.isEdit = false;
          row.isNew = false;
          delete this.tempDeliveryList[this.deliveryList.indexOf(row)];
          this.$message.success("保存成功");
          this.getDeliveryList();
        } else {
          this.$message.error(response.msg || "保存失败");
        }
      } catch (error) {
        console.error("保存成果交付失败:", error);
        this.$message.error("保存失败，请重试");
      }
    },

    handleCancelDeliveryEdit(index) {
      const row = this.deliveryList[index];
      if (row.isNew) {
        this.deliveryList.splice(index, 1);
      } else {
        this.deliveryList.splice(index, 1, { ...this.tempDeliveryList[index] });
      }
      delete this.tempDeliveryList[index];
    },

    handleRowDblClick(row) {
      // 如果已经在编辑状态,不做处理
      if (row.isEdit) return;

      // 保存原始数据用于取消编辑
      this.tempCostList[this.costList.indexOf(row)] = { ...row };

      // 设置行为编辑状态
      this.$set(row, "isEdit", true);
    },

    getBudgetList() {
      this.queryBudgetParams = {
        ...this.queryBudgetParams,
        processStage:
          (this.currentProcessData &&
            this.currentProcessData.processStageName) ||
          null,
        planningId:
          (this.currentProcessData && this.currentProcessData.planningId) ||
          null,
      };
      listBudget(this.queryBudgetParams).then(response => {
        this.costList = response.rows || [];
      });
    },

    // 新增行
    handleAddRow() {
      const newRow = {
        budgetId: this.guid(), // 在新增时就生成 budgetId
        planningId: this.currentProcessData.planningId,
        costDescription: "",
        costType: "",
        amount: null,
        costTime: "",
        processStage: this.currentProcessData.processStageName,
        isEdit: true,
        isNew: true,
      };
      this.costList.unshift(newRow);
    },

    // 保存行
    async handleSaveRow(row) {
      // 验证必填字段
      if (!row.costDescription || !row.costDescription.trim()) {
        this.$message.warning("请填写费用说明");
        return;
      }
      if (!row.costType || !row.costType.trim()) {
        this.$message.warning("请填写费用类型");
        return;
      }
      if (!row.amount || row.amount <= 0) {
        this.$message.warning("请输入正确的金额");
        return;
      }
      if (!row.costTime) {
        this.$message.warning("请选择产生时间");
        return;
      }

      try {
        const budgetData = {
          budgetId: row.budgetId,
          planningId: this.currentProcessData.planningId,
          costDescription: row.costDescription,
          costType: row.costType,
          amount: row.amount,
          costTime: row.costTime,
          processStage: this.currentProcessData.processStageName,
          useType: 3,
        };

        let response;
        if (row.isNew) {
          // 新增记录
          response = await addBudget(budgetData);
        } else {
          // 更新现有记录
          response = await updateBudget(budgetData);
        }

        if (response.code === 200) {
          // 更新成功后清除编辑状态
          row.isEdit = false;
          row.isNew = false;

          // 清除临时保存的数据
          delete this.tempCostList[this.costList.indexOf(row)];

          this.$message.success("保存成功");
          // 刷新列表
          this.getBudgetList();
        } else {
          this.$message.error(response.msg || "保存失败");
        }
      } catch (error) {
        console.error("保存费用记录失败:", error);
        this.$message.error("保存失败，请重试");
      }
    },
    // 取消编辑
    handleCancelEdit(index) {
      const row = this.costList[index];
      if (row.isNew) {
        // 如果是新增行,直接删除
        this.costList.splice(index, 1);
      } else {
        // 恢复原始数据
        this.costList.splice(index, 1, { ...this.tempCostList[index] });
      }
      // 清除临时数据
      delete this.tempCostList[index];
    },
    // 删除行
    handleDeleteRow(index) {
      const row = this.costList[index];
      this.$confirm("确认删除该费用记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (row.budgetId) {
            try {
              const response = await delBudget(row.budgetId);
              if (response.code === 200) {
                this.costList.splice(index, 1);
                this.$message.success("删除成功");
                // 刷新列表
                this.getBudgetList();
              } else {
                this.$message.error(response.msg || "删除失败");
              }
            } catch (error) {
              console.error("删除费用记录失败:", error);
              this.$message.error("删除失败，请重试");
            }
          } else {
            // 未保存的新记录，直接从列表中移除
            this.costList.splice(index, 1);
            this.$message.success("删除成功");
          }
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 导出当前数据
    handleExport() {
      if (this.selectedCosts.length === 0) {
        this.$message.warning("请至少选择一条记录进行导出");
        return;
      }
      // 获取选中记录的 ID 列表
      const selectedIds = this.selectedCosts.map(item => item.budgetId);
      // 构建导出参数
      const params = {
        planningId: this.currentProcessData.planningId,
        processStage: this.currentProcessData.processStageName,
        budgetIds: selectedIds.join(","),
      };

      // 调用导出接口
      this.download(
        "project/budget/export",
        params,
        `阶段施工费用数据_${new Date().getTime()}.xlsx`
      );
    },

    guid() {
      function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
      }

      return (
        S4() +
        S4() +
        "-" +
        S4() +
        "-" +
        S4() +
        "-" +
        S4() +
        "-" +
        S4() +
        S4() +
        S4()
      );
    },

    // 导出全部数据
    handleExportAll() {
      // 构建导出参数
      const params = {
        planningId: this.currentProcessData.planningId,
        processStage: this.currentProcessData.processStageName,
      };
      // 调用导出接口
      this.download(
        "project/budget/export",
        params,
        `阶段施工费用数据_全部_${new Date().getTime()}.xlsx`
      );
    },
    getList() {
      this.loading = true;
      this.queryParams.enterpriseId = this.enterpriseId;
      listPerson(this.queryParams).then(response => {
        this.personList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取项目信息
    getProjectInfo() {
      try {
        this.stageLoading = true;
        getImplementation(this.implementationId).then(response => {
          const data = response.data;
          this.projectId = data.projectId;
          // 回显项目基本信息
          this.projectForm = {
            projectId: data.projectId || "",
            projectNumber: data.projectNumber || "",
            projectName: data.projectName || "",
            plannedStartTime: data.plannedStartTime.substring(0, 10) || "",
            plannedEndTime: data.plannedEndTime.substring(0, 10) || "",
            actualStartTime:
              data.actualStartTime == null
                ? data.plannedStartTime.substring(0, 10)
                : data.actualStartTime.substring(0, 10),
            actualEndTime:
              data.actualEndTime == null
                ? data.plannedEndTime.substring(0, 10)
                : data.actualEndTime.substring(0, 10),
            productName: data.productName || "",
          };
          const useType = 3;
          const id = data.projectPlanningId;
          getProjectPlanning(id, useType)
            .then(res => {
              // 处理并排序processes数据
              const sortedProcesses = res.data.processes.sort(
                (a, b) => a.processStageOrder - b.processStageOrder
              );
              // 转换为stages数据
              this.stages = sortedProcesses.map((process, index) => ({
                ...process, // 根据实际状态判断
              }));

              // 默认选中第一个阶段
              if (this.stages.length > 0) {
                this.selectStage(0);
              }
            })
            .finally(() => {
              this.stageLoading = false;
            });
        });
      } catch (error) {
        console.error("获取项目信息失败:", error);
        this.$message.error("获取项目信息失败");
        this.stageLoading = false;
      }
    },

    // 选择阶段
    async selectStage(index) {
      // 保存当前阶段的表单数据
      this.saveCurrentStageData();
      this.selectedStage = index;
      const selectedProcess = this.stages[index];
      this.currentProcessData = selectedProcess;
      this.stageActiveTab = "serviceLog";
      // 获取当前阶段的费用数据
      this.getBudgetList();
      this.getDeliveryList();
      // 检查是否有已保存的表单数据
      const savedFormData = this.stageFormsData[selectedProcess.processStageId];
      // 更新阶段表单数据
      this.stageForm = {
        processId: selectedProcess.processId || "",
        plannedStartTime:
          this.formatDate(selectedProcess.plannedStartTime) || "",
        plannedEndTime: this.formatDate(selectedProcess.plannedEndTime) || "",
        actualStartTime:
          savedFormData && savedFormData.actualStartTime
            ? this.formatDate(savedFormData.actualStartTime)
            : selectedProcess.actualStartTime
            ? this.formatDate(selectedProcess.actualStartTime)
            : null,
        actualEndTime:
          savedFormData && savedFormData.actualEndTime
            ? this.formatDate(savedFormData.actualEndTime)
            : selectedProcess.actualEndTime
            ? this.formatDate(selectedProcess.actualEndTime)
            : null,
        executorPerson: selectedProcess.executorPerson
          ? selectedProcess.executorPerson.toString()
          : "",
        status:
          savedFormData && savedFormData.status !== undefined
            ? Number(savedFormData.status) // 确保转换为数字
            : Number(selectedProcess.status) || 0,
      };

      if (selectedProcess.executorPerson) {
        try {
          const response = await getUser(selectedProcess.executorPerson);
          this.executorPersonName =
            response.data.nickName || response.data.userName || "";
        } catch (error) {
          console.error("获取执行人信息失败:", error);
          this.$message.error("获取执行人信息失败");
          this.executorPersonName = "";
        }
      } else {
        this.executorPersonName = "";
      }
    },
    saveCurrentStageData() {
      if (this.currentProcessData && this.stageForm) {
        this.stageFormsData[this.currentProcessData.processStageId] = {
          ...this.stageForm,
          status: Number(this.stageForm.status),
        };
      }
    },
    toggleCollapse() {
      this.isExpanded = !this.isExpanded;
    },

    indexMethod(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },
    cancel() {
      // 在关闭前保存当前阶段数据
      this.saveCurrentStageData();
      getImplementation(this.implementationId)
        .then(response => {
          const data = response.data;
          if (!data.actualStartTime) {
            this.$confirm(
              "检测到数据未保存，是否确认关闭？关闭后新增的数据将被删除",
              "提示",
              {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }
            )
              .then(() => {
                deleteServiceLogByProjectId(data.projectId).then(res => {});
                deleteProjectBudget(this.currentProcessData.planningId).then(
                  res => {}
                );
                this.$emit("change");
              })
              .catch(() => {
                this.$message.info("已取消关闭");
              });
          } else {
            this.$emit("change");
          }
        })
        .catch(error => {
          console.error("获取项目信息失败:", error);
          this.$message.error("获取项目信息失败");
        });
    },

    submitForm() {
      this.$refs.stageForm.validate(valid => {
        if (valid) {
          this.saveCurrentStageData();
          const processesArray = this.stages.map(stage => {
            const stageData = this.stageFormsData[stage.processStageId] || {};
            return {
              processId: stage.processId || "",
              processStageId: stage.processStageId,
              actualStartTime: stageData.actualStartTime || null,
              actualEndTime: stageData.actualEndTime || null,
              executorPerson: stageData.executorPerson || null,
              // 添加其他必要的字段
              processStageOrder: stage.processStageOrder,
              processStageName: stage.processStageName,
              status: Number(stageData.status || 0),
            };
          });
          const data = {
            projectId: this.projectForm.projectId,
            actualStartTime: this.projectForm.actualStartTime,
            actualEndTime: this.projectForm.actualEndTime,
            projectBudgets: this.costList,
            processes: processesArray,
          };
          editProjectImplementation(data).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.$emit("change");
          });
        }
      });
    },

    validateActualTime() {
      this.$refs.stageForm.validateField("actualTimeRange");
    },
    formatDate(date) {
      if (!date) return "";
      if (typeof date === "string") {
        // 如果已经是 YYYY-MM-DD 格式，直接返回
        if (date.length === 10) return date;
        // 否则尝试转换
        date = new Date(date);
      }
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    // 删除成果交付
    handleDeleteDelivery(row) {
      this.$confirm("确认删除该成果交付记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delDeliverable(row.deliverableId)
            .then(response => {
              if (response.code === 200) {
                this.$message.success("删除成功");
                // 刷新列表数据
                this.getDeliveryList();
              } else {
                this.$message.error(response.msg || "删除失败");
              }
            })
            .catch(error => {
              console.error("删除成果交付记录失败:", error);
              this.$message.error("删除失败，请重试");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    handleUploadClick(row) {
      this.currentDeliveryId = row.deliverableId;
      this.uploadDialogVisible = true;
      this.refreshKey++; // 刷新 FileView 组件
    },

    // 处理文件变化
    handleFileChange(data) {
      console.log("文件变化:", data);
    },

    // 处理上传确认
    handleUploadConfirm() {
      this.uploadDialogVisible = false;
      this.$message.success("附件上传成功");
      this.getDeliveryList(); // 刷新列表
    },

    handleView(row) {
      if (row.url != null && row.url != "" && row.url.indexOf(".pdf") !== -1) {
        this.handlePictureCardPreviewPdf(row.url);
      } else {
        this.handlePictureCardPreview(row.url);
      }
    },

    handlePictureCardPreview(url) {
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },
    handlePictureCardPreviewPdf(url) {
      this.pdfUrl = pdf.createLoadingTask(url);
      // 获取页码
      this.pdfUrl.promise
        .then(pdf => (this.pageTotal = pdf.numPages))
        .catch(error => {});
      this.dialogImageUrlPdf = url;
      this.dialogVisiblePdf = true;
    },

    handleDownload(fileUrl, fileName) {
      let params = {
        resource: fileUrl,
      };
      download("/common/download/resource", params, fileName);
    },
    queryUploadFile(id) {
      queryFile(id, "stageDeliverable").then(response => {
        this.fileList = response.data;
      });
      this.viewDialogVisible = true;
    },
    // 判断阶段是否已开始（检查是否有相关数据）
    async checkStageStarted(stage) {
      try {
        // 1. 检查服务日志
        const hasServiceLogs = await this.checkServiceLogs(
          stage.processStageId
        );

        // 2. 检查施工费用
        const hasCosts = this.costList.some(
          cost => cost.processStage === stage.processStageName
        );

        // 3. 检查成果交付
        const hasDeliverables = this.deliveryList.some(
          delivery => delivery.processId === stage.processId
        );

        return hasServiceLogs || hasCosts || hasDeliverables;
      } catch (error) {
        console.error("检查阶段状态失败:", error);
        return false;
      }
    },

    // 判断阶段是否已过期
    isStageOverdue(stage) {
      const now = new Date();
      const plannedEndTime = new Date(stage.plannedEndTime);
      return now > plannedEndTime;
    },

    // 判断阶段是否正在进行中
    async isStageInProgress(stage) {
      // 检查阶段是否已开始
      return await this.checkStageStarted(stage);
    },

    // 更新阶段显示状态
    async updateStageStatus() {
      for (const stage of this.stages) {
        const isStarted = await this.checkStageStarted(stage);
        const isOverdue = this.isStageOverdue(stage);

        // 更新阶段状态
        this.$set(stage, "displayStatus", {
          isCompleted: stage.status === 1, // 已完成
          isStarted, // 已开始
          isOverdue, // 已过期
        });
      }
    },
  },
};
</script>

<style scoped lang="scss">
.project-operate-container {
  overflow-y: auto;
  overflow-x: auto;
  padding: 16px;
  max-width: 100%;
  max-height: 90vh;
  box-sizing: border-box;
}

.card-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.collapse-header {
  cursor: pointer;
  padding: 5px 0;
  user-select: none;
  text-align: center;
  /* 添加以下样式 */
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 50px;
  height: 24px;
  line-height: 24px;
  margin: 10px auto;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

/* 添加悬停效果 */
.collapse-header:hover {
  border-color: #409eff;
  color: #409eff;
}

.collapse-header:hover i {
  color: #409eff;
}

.collapse-header i {
  transition: all 0.3s;
  font-size: 14px;
  color: #909399;
  display: inline-block;
}

.collapse-header i.is-active {
  transform: rotate(90deg);
}

.collapse-content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease-out;
}

.collapse-content.is-expanded {
  max-height: 500px;
}

.stage-title {
  font-size: 12px;
  font-weight: 700;
  color: #606266;
  width: 6%;
  white-space: nowrap;
  position: relative;
  top: 54px;
  left: 40px;
}

.stage-flow {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 0;
  margin-left: 20px;
  min-height: 100px;
  position: relative;
  left: 100px;
}

.stage-node-wrapper {
  display: flex;
  align-items: center;
}

.stage-node {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.node-circle {
  width: 66px; /* 进一步增大圆圈 */
  height: 66px;
  border-radius: 50%;
  background-color: #fff;
  border: 2px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #909399;
  transition: all 0.3s;
  margin-bottom: 10px;
  padding: 0 5px;
}

.stage-line {
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 3px;
  background-color: #409eff;
  transition: width 0.3s ease;
}

.stage-node.selected .stage-line {
  width: 100%;
}

.stage-arrow {
  width: 60px;
  height: 2px;
  background-color: #dcdfe6;
  position: relative;
  margin: 0 5px;
}

.stage-arrow::after {
  content: "";
  position: absolute;
  right: 0;
  top: 50%;
  width: 8px;
  height: 8px;
  border-top: 2px solid #dcdfe6;
  border-right: 2px solid #dcdfe6;
  transform: translate(0, -50%) rotate(45deg);
}

/* 已完成节点样式（红色）- 优先级最高 */
.stage-node.active .node-circle {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
  box-shadow: 0 0 10px rgba(245, 108, 108, 0.3);
}

/* 进行中且未过期节点样式（绿色） */
.stage-node.current .node-circle {
  background-color: #67c23a;
  border-color: #67c23a;
  color: #fff;
  box-shadow: 0 0 10px rgba(103, 194, 58, 0.3);
}

/* 已过期节点样式（紫色）- 包括未开始和进行中但未完成的 */
.stage-node.overdue .node-circle {
  background-color: #8e44ad;
  border-color: #8e44ad;
  color: #fff;
  box-shadow: 0 0 10px rgba(142, 68, 173, 0.3);
}

/* 未开始且未过期节点样式（白色）- 默认样式 */
.stage-node .node-circle {
  background-color: #fff;
  border-color: #dcdfe6;
  color: #909399;
}

.text-center {
  text-align: center;
  line-height: 32px;
}

/* 阶段标签页样式 */
.stage-tabs {
  margin-top: 20px;
}

::v-deep .el-tabs__nav-wrap::after {
  height: 1px;
}

::v-deep .el-tabs__item {
  height: 40px;
  line-height: 40px;
}

::v-deep .el-tabs__active-bar {
  height: 3px;
}

.bottom-buttons {
  margin-top: 20px;
  text-align: center;
}

/* 表单样式调整 */
::v-deep .el-form-item {
  margin-bottom: 18px;
}

::v-deep .el-form-item__label {
  padding-right: 20px;
}

/* 按钮样式 */
.el-button {
  padding: 9px 20px;
}

.el-button + .el-button {
  margin-left: 10px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .stage-flow {
    margin-left: 10px;
  }

  .stage-node-wrapper {
    margin: 0 5px;
  }

  .node-circle {
    width: 56px;
    height: 56px;
    font-size: 12px;
  }

  .stage-arrow {
    width: 30px;
  }

  .stage-line {
    bottom: -8px;
    height: 2px;
  }
}

.operation-group {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.operation-group .el-button {
  margin-left: 10px;
  margin-right: 0;
}

.operation-group .el-button:first-child {
  margin-left: 0;
}

/* 表格内按钮样式调整 */
.el-table .el-button--mini {
  padding: 4px 10px;
}

.el-input.is-disabled .el-input__inner {
  color: #606266;
}

.el-date-editor.el-input {
  width: 100%;
}

/* 调整表格列宽 */
.el-table {
  margin-top: 10px;
}

/* 金额列右对齐 */
.el-table .el-input-number.is-controls-right {
  width: 100%;
}

/* 日期选择器样式优化 */
.el-date-editor.el-input--mini {
  width: 100%;
}

/* 编辑状态下的输入框样式 */
.el-table .el-input--mini .el-input__inner {
  height: 28px;
  line-height: 28px;
}

::v-deep .el-table .el-table__header .el-checkbox {
  margin-bottom: 0;
}

::v-deep .el-table .el-checkbox {
  margin-right: 0;
}

::v-deep .el-table .el-table-column--selection .cell {
  padding-right: 10px;
  padding-left: 10px;
}

.service-log-content {
  min-height: 200px;
}

/* 添加内容过渡效果 */
.el-tab-pane {
  transition: opacity 0.3s ease;
}

/* 标签页内容区域固定高度 */
::v-deep .el-tabs__content {
  position: relative;
}
</style>
